package com.zhongxi.guoyuan.view.rewardCoin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.adapter.GvShopSlidingAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoin.RewardCoinAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.rewardcoin.MallShopDetail;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardShopInfo;

import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.beautifulStore.SubscribeActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/17.
 */

public class RewardCoinShoperAtivity extends BaseActivity implements View.OnClickListener, MyScrollView.OnScrollListener {

    private String shopid;
    private List<ProjectItemData> list = new ArrayList<ProjectItemData>();
    private RelativeLayout rl_content;
    private RatingBar rb;
    private TextView tv_shop_recommend;
    private LinearLayout ll_shopper_desc;
    private TextView post_shop_phone;
    private TextView post_shop_address;
    private TextView tvSellCategory;
    private NoScrollGridView gvList;

    private NoScrollGridView gridView;
    private FrameLayout flow;
    private MyScrollView myScrollView;
    private LinearLayout relaLayout;
    private LinearLayout scrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private int scrollHeight;
    private String type;
    private ViewFlow viewflow;
    private CircleIndicator viewflowdic;
    private BannerAdapter bannerAdapter;
    private TextView tvStoreName;
    private String s;
    private GvShopSlidingAdapter gvAdapter;
    private String order = "0";
    private String innerCategory = "0";
    private boolean isLoadMore;
    private List<HotGoodsData> data = new ArrayList<>();
    private RewardCoinAdapter listAdapter;
    private ProgressDialog mDialog;
    private PopupWindow pw;
    private RewardShopInfo rewardShopInfo;
    public static final int requestFulsh = 500;
    public static final int requestFulshConver = 600;
    private HotGoodsResult mallGoodList;

    private int mFlag;
    private RelativeLayout mRelative_search;


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            scrollHeight = relaLayout.getBottom();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_reward_coin_shoper);
        initTitle();
        tvTitle.setText("线上赚豆超市商家详情");
        shopid = getIntent().getStringExtra("shopid");
        list.add(new ProjectItemData("0", "全部", "", false));
        mFlag = getIntent().getIntExtra("flag", 0);
        rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        tvStoreName = (TextView) findViewById(R.id.tvStoreName);
        rb = (RatingBar) findViewById(R.id.rb);
        tv_shop_recommend = (TextView) findViewById(R.id.tv_shop_recommend);

        ll_shopper_desc = (LinearLayout) findViewById(R.id.ll_shopper_desc);
        ll_shopper_desc.setVisibility(View.GONE);
        post_shop_phone = (TextView) findViewById(R.id.post_shop_phone);
        post_shop_address = (TextView) findViewById(R.id.post_shop_address);
        tvSellCategory = (TextView) findViewById(R.id.tvSellCategory);
        mRelative_search = (RelativeLayout) findViewById(R.id.relative_search);

        gvList = (NoScrollGridView) findViewById(R.id.gvList);
        gridView = (NoScrollGridView) findViewById(R.id.gridView);

        //实现上拉布局悬停
        initScrollPause();
        flow = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.detailRate, flow);
    }

    private void initScrollPause() {
        myScrollView = (MyScrollView) findViewById(R.id.myScrollView);
        relaLayout = (LinearLayout) findViewById(R.id.relaLayout);
        scrollBody = (LinearLayout) findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
    }

    @Override
    protected void initData() {
        super.initData();
        listAdapter = new RewardCoinAdapter(context, data);
        gridView.setAdapter(listAdapter);
        type = "detail";
        String str = "&shopid=" + shopid;
        getServer(Url.MALL_SHOP_DETAILS, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tv_shop_recommend.setOnClickListener(this);

        myScrollView.setOnScrollListener(this);
        rl_content.setOnClickListener(this);
        mRelative_search.setOnClickListener(this);
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long lon) {
                if (pos > 0) {
                    innerCategory = list.get(pos).getId();
                } else {
                    innerCategory = "0";
                }
                data.clear();
                listAdapter.notifyDataSetChanged();
                gvAdapter.setSelectIndex(pos);
                gvAdapter.notifyDataSetChanged();
                pageNum = 1;
                getShopGoodList();

            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String id = mallGoodList.getGoodsInfo().get(i).getId();
                Intent intent = new Intent(RewardCoinShoperAtivity.this, RewardCoinDetailActivity.class);
                intent.putExtra("gid", id);
                startActivity(intent);

            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (4 == mFlag) {
            startAct(MainHomeActivity.class);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                if (4 == mFlag) {
                    startAct(MainHomeActivity.class);
                }
                break;
            case R.id.tv_shop_recommend:
                int visibility = ll_shopper_desc.getVisibility();
                if (visibility == 0) {
                    tv_shop_recommend.setTextColor(getResources().getColor(R.color.bg_yield));
                    ll_shopper_desc.setVisibility(View.GONE);
                } else {
                    tv_shop_recommend.setTextColor(getResources().getColor(R.color.white));
                    ll_shopper_desc.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rl_content:
                if (CommonTool.checkApkExist(RewardCoinShoperAtivity.this, "com.tencent.mobileqq")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin=" + Constants.QQ_NUM + "&version=1")));
                } else {
                    showShortToast("未安装QQ");
                }
                break;
            case R.id.relative_search:
                startAct(SearchActivity.class);
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if ("detail".equals(type)) {
            MallShopDetail mallShopDetail = gson.fromJson(response, MallShopDetail.class);
            if (mallShopDetail.getSafeobj() != null && !"".equals(mallShopDetail.getSafeobj())) {
                MyApplication.getInstance().setSpValue(mallShopDetail.getSafeobj());
            }
            if (mallShopDetail.getShopInfo() != null && !"".equals(mallShopDetail.getShopInfo())) {
                rewardShopInfo = mallShopDetail.getShopInfo();
                if ("0".equals(rewardShopInfo.getStatus())) {
                    finish();
                    showShortToast("该店铺已关闭");
                    return;
                }
                if (rewardShopInfo.getImages() != null && rewardShopInfo.getImages().size() > 0) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopImage", rewardShopInfo.getImages().get(0)).commit();
                    lunBo(rewardShopInfo.getImages());
                }
                getShopInfo(rewardShopInfo);
            }
            if (mallShopDetail.getInnerCategory() != null && mallShopDetail.getInnerCategory().size() > 0) {
                List<ProjectItemData> InnerCategory = mallShopDetail.getInnerCategory();
                list.addAll(InnerCategory);
                gvAdapter = new GvShopSlidingAdapter(context, list);
                gvList.setAdapter(gvAdapter);
                setGvParams(gvList, list, 4);
            }
            getShopGoodList();
        } else if ("shopGoodList".equals(type)) {
            mallGoodList = gson.fromJson(response, HotGoodsResult.class);
            MyApplication.getInstance().setSpValue(mallGoodList.getSafeobj());
            if (isLoadMore) {
                if (null == mallGoodList.getGoodsInfo() || mallGoodList.getGoodsInfo().size() == 0) {
                    showShortToast("没有加载更多了");
                    return;
                }
            }
            if (pageNum == 1) {
                data.clear();

                if (null == mallGoodList.getGoodsInfo() || mallGoodList.getGoodsInfo().size() == 0) {
                    listAdapter.notifyDataSetChanged();
                    showShortToast("无数据");
                    return;
                }
            }
            if (null != mallGoodList.getGoodsInfo() && mallGoodList.getGoodsInfo().size() > 0) {
                data.addAll(mallGoodList.getGoodsInfo());
                listAdapter = new RewardCoinAdapter(context, data);
                gridView.setAdapter(listAdapter);
            }
            listAdapter.notifyDataSetChanged();
        }
    }


    private void getShopGoodList() {
        type = "shopGoodList";
        String str = "&shopid=" + shopid + "&goodstype=" + order + "&innerCategory=" + innerCategory + "&page=" + pageNum;
        getServer(Url.REWARD_SHOP_GOODS_LIST, null, str, false, null, "get");
    }

    //设置gridView的属性
    private void setGvParams(NoScrollGridView gv, List list, int item) {
        int spaceWith = CommonTool.dip2px(context, 10);//左边距 paddingLeft
        int with = getResources().getDisplayMetrics().widthPixels / item;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(list.size() * with, LinearLayout.LayoutParams.WRAP_CONTENT);
        gv.setLayoutParams(params);
        gv.setColumnWidth(with - spaceWith);
        gv.setHorizontalSpacing(spaceWith);
        gv.setStretchMode(GridView.NO_STRETCH);   //不拉伸
        gv.setOverScrollMode(0);
        gv.setNumColumns(list.size());      //一排显示几列
    }

    private void lunBo(List<String> images) {
        viewflow = (ViewFlow) findViewById(R.id.viewflow);
        viewflowdic = (CircleIndicator) findViewById(R.id.viewflowdic);
        viewflow.setFlowIndicator(viewflowdic);
        viewflow.setSideBuffer(images.size());
        if (bannerAdapter == null) {
            bannerAdapter = new BannerAdapter(this, images);
        } else {
            bannerAdapter.replaceAll(images);
        }
        viewflow.setAdapter(bannerAdapter);
        viewflow.startAutoFlowTimer();
    }

    private void getShopInfo(RewardShopInfo rewardShopInfo) {
        if (rewardShopInfo.getName() != null && !"".equals(rewardShopInfo.getName())) {
            tvStoreName.setText(rewardShopInfo.getName());
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopName", rewardShopInfo.getName()).commit();
        } else {
            tvStoreName.setText("");
        }
        if (rewardShopInfo.getStarlevel() != null && !"".equals(rewardShopInfo.getStarlevel())) {
            rb.setRating(Float.parseFloat(rewardShopInfo.getStarlevel()));
        } else {
            rb.setRating(Float.parseFloat("1.0"));
        }
        if (rewardShopInfo.getPhone() != null && !"".equals(rewardShopInfo.getPhone())) {
            post_shop_phone.setText(rewardShopInfo.getPhone());
            s = MD5Tool.Md5(rewardShopInfo.getPhone());
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopPhone", s.substring(s.length() - 16, s.length())).commit();
        } else {
            post_shop_phone.setText("");
        }
        if (rewardShopInfo.getAddress() != null && !"".equals(rewardShopInfo.getAddress())) {
            post_shop_address.setText(rewardShopInfo.getAddress());
        } else {
            post_shop_address.setText("");
        }
        if (rewardShopInfo.getSubject() != null && !"".equals(rewardShopInfo.getSubject())) {
            tvSellCategory.setText(rewardShopInfo.getSubject());
        } else {
            tvSellCategory.setText("");
        }

    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (baseResponse.getSafeobj() != null && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
        if (baseResponse.getCode() == 1000) {
            showShortToast("店铺已关闭");
            finish();
        }
        if (baseResponse.getCode() == 5000) {
            if (isLoadMore) {
                showShortToast("商品信息不完善");
                return;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestFulsh) {
            pw.dismiss();
        } else if (requestCode == requestFulshConver) {
            pw.dismiss();
        }
    }


    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= scrollHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(scrollBody.getMeasuredWidth(), scrollBody.getMeasuredHeight()));
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
    }

}
